package cn.haocxy.jfm.gui;

import java.util.ArrayList;
import java.util.Collection;

import javafx.scene.control.MenuItem;
import cn.haocxy.jfm.file.Clipboard;
import cn.haocxy.jfm.file.Clipboard.Mode;
import cn.haocxy.jfm.file.FilePath;
import cn.haocxy.jfm.filelist.FileItem;
import cn.haocxy.jfm.func.FileFunc;
import cn.haocxy.jfm.func.GUIFunc;

/**
 * 当前文件项处于一组被选中的文件项中时
 * 
 * @author 蔡心宇
 *
 */
class FileItemMenuMulti extends FileItemMenu {

	private final MenuItem copy;
	
	private final MenuItem cut;
	
	private final MenuItem remove;
	
	public FileItemMenuMulti() {
		super();

		copy = add("复制", this::copy);
		cut = add("剪切", this::cut);
		addSep();
		remove = add("删除", this::remove);
		
	}
	
	@Override
	protected void filt() {
		filt(copy, menuItem->filtCopy());
		filt(cut, menuItem->filtCut());
		filt(remove, menuItem->filtRemove());
	}
	
	private boolean filtCopy() {
		for (FileItem item : getFileList().getSelectedItems()) {
			if (!item.toFilePath().isReadable()) {
				return false;
			}
		}
		return true;
	}
	
	private boolean filtCut() {
		for (FileItem item : getFileList().getSelectedItems()) {
			FilePath p = item.toFilePath();
			if (!(p.isReadable() && p.isWritable())) {
				return false;
			}
		}
		return true;
	}
	
	private boolean filtRemove() {
		for (FileItem item : getFileList().getSelectedItems()) {
			FilePath p = item.toFilePath();
			if (!p.isWritable()) {
				return false;
			}
		}
		return true;
	}
	
	private void copy() {
		Clipboard cb = Clipboard.get();
		cb.setMode(Mode.COPY);
		Collection<FileItem> items = getFileList().getSelectedItems();
		ArrayList<FilePath> paths = new ArrayList<>(items.size());
		for (FileItem item : items) {
			paths.add(item.toFilePath());
		}
		cb.add(paths);
	}
	
	private void cut() {
		Clipboard cb = Clipboard.get();
		cb.setMode(Mode.MOVE);
		Collection<FileItem> items = getFileList().getSelectedItems();
		ArrayList<FilePath> paths = new ArrayList<>(items.size());
		for (FileItem item : items) {
			paths.add(item.toFilePath());
		}
		cb.add(paths);
	}
	
	private void remove() {
		int size = getFileList().selectedNum();
		boolean ok;
		ok = GUIFunc.confirm(getCurrentWindow(), 
				"删除后无法恢复 , 确认删除" + size + "项文件吗?");
		
		if (ok) {
			Collection<FileItem> items = getFileList().getSelectedItems();
			ArrayList<FilePath> paths = new ArrayList<>(items.size());
			for (FileItem item : items) {
				paths.add(item.toFilePath());
			}
			FileFunc.remove(paths, null);
		}
	}
	
}
